using System;
using UnityEngine;
public class MoveAlongBezier : MonoBehaviour
{
    public Transform[] waypoints;
    public float duration = 5f;
    private float startTime;
    private void OnEnable()
    {
        startTime = Time.time;
    }
    void Update()
    {
        float t = (Time.time - startTime) / duration;
        if (t > 1f) t = 1f;
        transform.position = CalculateCubicBezierPoint(t,
            waypoints[0].position,
            waypoints[1].position,
            waypoints[2].position,
            waypoints[3].position);
        if (t == 1f) enabled = false;
        Debug.Log(transform.position);
    }
    Vector3 CalculateCubicBezierPoint(float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3)
    {
        // 三次贝塞尔曲线公式
        float u = 1 - t;
        float tt = t * t;
        float uu = u * u;
        float uuu = uu * u;
        float ttt = tt * t;
        Vector3 p = uuu * p0;
        p += 3 * uu * t * p1;
        p += 3 * u * tt * p2;
        p += ttt * p3;
        return p;
    }
}